//
//  StudentListTableViewController.m
//  Eath
//
//  Created by yuhaya on 14-9-20.
//  Copyright (c) 2014年 yuhaya. All rights reserved.
//

#import "StudentListTableViewController.h"
#import "StudentListTableViewCell.h"
#import "Tool.h"
#import "StudentDetailViewController.h"
#import "StudentBaseViewController.h"
#import "StudentAddViewController.h"
#import "RemindViewController.h"
#import "GenearchListTableViewController.h"
#import "User.h"
#import "RelationViewController.h"
#import "Database.h"

@interface StudentListTableViewController ()

@end

static NSString * cellId = @"student_cell_id";

@implementation StudentListTableViewController




- (id)init {
    self = [super init];
    if (self != nil) {
        self.operate = 1;
        self.gen_id = nil;
    }
    return self;
}

- (void)stus_load_over
{
    self.studentListData = [self.stuList getStudentList];
    DLog(@"%@",self.studentListData);
    [self.tableView reloadData];
}

- (void)stus_load_fail
{

}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    UILabel *customLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    [customLab setTextColor:[UIColor whiteColor]];
    if(self.operate == 6){
    
        [customLab setText:@"请选择学生"];
    }else if(self.operate == 5){
    
        [customLab setText:@"监管的学生列表"];
    }else{
        [customLab setText:@"学生列表"];
    }
    customLab.textAlignment = NSTextAlignmentCenter;
    customLab.font = [UIFont boldSystemFontOfSize:16];
    self.navigationItem.titleView = customLab;
    UINib *nib = [UINib nibWithNibName:@"StudentListTableViewCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:cellId];
//    if(self.stuList == nil){
        StudentList * stu_list;
        
        if(self.gen_id == nil){
        
            stu_list = [[StudentList alloc] init];
        }else{
            stu_list = [[StudentList alloc] initWithGen:self.gen_id];
            DLog(@"--------%@",self.gen_id);
        }
        stu_list.detegate = self;
        self.stuList = stu_list;
        self.studentListData = [stu_list getStudentList];
//    }
    
    
    if(self.operate == 2){
        //添加学生
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addStu)];
    }else if (self.operate == 5){
        //给家长添加一个学生
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"添加" style:UIBarButtonItemStyleBordered target:self action:@selector(add_controller_stu)];
    }
    
    
}
/**
 *  添加学生管理
 */
-(void)add_controller_stu
{
        NSDictionary * userinfo = [User loginInfo];
        StudentListTableViewController * stu_all_list = [[StudentListTableViewController alloc] init];
        stu_all_list.gen_id = userinfo[@"id"];
        stu_all_list.sub_gen_id = self.gen_id;
        DLog(@"--%@",stu_all_list.gen_id);
        stu_all_list.operate = 6;
        [self.navigationController pushViewController:stu_all_list animated:YES];
}

/**
 *  添加学生
 */
- (void)addStu
{
    StudentAddViewController * stu_add = [[StudentAddViewController alloc] init];
    [self.navigationController pushViewController:stu_add animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return [self.studentListData count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    StudentListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
    
    // Configure the cell...
    Student * stu = self.studentListData[indexPath.row];
    cell.user_name.text = stu.name;
    cell.edu_msg.text = stu.grade;
    NSInteger sexCode = stu.sex;
    cell.sex.text = sexCode == 0 ? @"男" : @"女";
    cell.user_photo.layer.cornerRadius = cell.user_photo.frame.size.width/2;
    cell.user_photo.layer.shouldRasterize = YES;
    cell.user_photo.layer.masksToBounds = YES;
    [cell.user_photo.layer setBorderWidth:3];
    [cell.user_photo.layer setBorderColor:[Tool colorWithHexString:@"#ffffff"].CGColor];
    cell.contentMode = UIViewContentModeScaleAspectFit;
    
    UIView *bgView = [[UIView alloc] init];
    bgView.backgroundColor = [[UIColor alloc]initWithRed:250.0/255.0 green:250.0/255.0 blue:250.0/255.0 alpha:1];
    cell.backgroundView = bgView;
    
    UIView *bgColorView = [[UIView alloc] init];
    bgColorView.backgroundColor = [UIColor colorWithRed:(240.0/255.0) green:(240.0/255.0) blue:(240.0/255.0) alpha:1.0];
    bgColorView.layer.masksToBounds = YES;
    cell.selectedBackgroundView = bgColorView;
    
    if(self.operate == 1 || self.operate == 2){
        UIButton *button = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        CGRect frame = button.frame;
        frame.size.width = 50;
        frame.size.height = 50;
        button.frame = frame;
        button. backgroundColor = [UIColor clearColor];
        [button addTarget:self action:@selector(btnClicked: event:) forControlEvents:UIControlEventTouchUpInside ];
        cell.accessoryView = button;
    }
    
    if(self.operate == 6){
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    return cell;
}

- (void)btnClicked:(id)sender event:(id)event
{
    NSSet *touches = [event allTouches];
    UITouch *touch = [touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:currentTouchPosition];
    if (indexPath != nil)
    {
        [self tableView: self.tableView accessoryButtonTappedForRowWithIndexPath:indexPath];
    }
}

-(void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
    RemindViewController * remind = [[RemindViewController alloc] init];
    remind.stu = self.studentListData[indexPath.row];
    [self.navigationController pushViewController:remind animated:YES];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(self.operate == 1){
        
        StudentDetailViewController * stuDetail = [[StudentDetailViewController alloc] init];
        stuDetail.stu = self.studentListData[indexPath.row];
        [self.navigationController pushViewController:stuDetail animated:YES];
        
    }else if(self.operate == 2){
        
        StudentBaseViewController * stuBase = [[StudentBaseViewController alloc] init];
        stuBase.stu = self.studentListData[indexPath.row];
        [self.navigationController pushViewController:stuBase animated:YES];
    
    }else if (self.operate == 3){
        
        RemindViewController * remind = [[RemindViewController alloc] init];
        remind.stu = self.studentListData[indexPath.row];
        [self.navigationController pushViewController:remind animated:YES];
    }else if(self.operate == 4){
//        [Tool showMessage:@"获取学生监护人的信息接口未开通"];
//        return;
        GenearchListTableViewController * genList = [[GenearchListTableViewController alloc] init];
        genList.purpose = 2;
        genList.stu = self.studentListData[indexPath.row];
        [self.navigationController pushViewController:genList animated:YES];
    }else if(self.operate == 5){
    
        RelationViewController * relation = [[RelationViewController alloc] init];
        relation.gen_id = self.gen_id;
        Student * stu = self.studentListData[indexPath.row];
        relation.stu_id = stu.identify;
        relation.relation_val = stu.relation;
        [self.navigationController pushViewController:relation animated:YES];
        
    }else if(self.operate == 6){
        RelationViewController * relation = [[RelationViewController alloc] init];
        relation.gen_id = self.sub_gen_id;
        Student * stu = self.studentListData[indexPath.row];
        relation.stu_id = [NSString stringWithFormat:@"%@",stu.identify];
        [self.navigationController pushViewController:relation animated:YES];
    }
}

#pragma mark - table 编辑删除

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(self.operate == 1){
        return NO;
    }else{
        return YES;
    }
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(self.operate == 2){
        //删除学生
        Student * stu = self.studentListData[indexPath.row];
        Boolean flag = [self.stuList deleteStu:stu.identify];
        if(flag){
            Student * stu = self.studentListData[indexPath.row];
            NSString * token = [User token];
            NSDictionary * parameters = [NSDictionary dictionaryWithObjectsAndKeys:stu.identify,@"student_id",nil];
            
            AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
            NSString * url_stus_get = [NSString stringWithFormat:@"%@?token=%@",URL_STU_DEL,token];
            DLog(@"%@",parameters);
            [manager POST:url_stus_get parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
                
                NSDictionary * redata = responseObject;
//                NSArray * data = redata[@"data"];
                NSString * code = redata[@"code"];
                
                if(code.intValue  == 0){
//                    DLog(@"%@",data);
                    [Tool showMessage:@"删除成功！"];
                    [[Database sharedDatabase] syncStudents:self.gen_id];
//                    self.studentListData = [self.stuList getStudentList];
//                    [self.tableView reloadData];
                    
                }else{
                    [Tool showMessage:redata[@"msg"]];
                }
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [Tool showMessage:@"删除学生失败！"];
            }];
            
        }else{
            [Tool showMessage:@"删除失败！"];
        }
        
    }else if(self.operate == 5){
        //解除家长与学生的关系
       [Tool showMessage:@"解除家长与学生的关系!"];
    }
    
}

@end
